package com.xuhuan.thread.study2.example;

/**
 * @author huan.xu
 * @date 2021/9/28 19:42
 * @description 龟兔赛跑
 */
public class ThreadRace implements Runnable {

    private static String winner;

    @Override
    public void run() {
        for (int i = 1; i <= 100; i++) {
            if (gameOver(i)) {
                break;
            }
            if (getThreadName().equals("兔子") && i % 10 == 0) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }
            System.out.println(getThreadName() + "---->跑了" + i + "步");
        }

    }

    private String getThreadName() {
        return Thread.currentThread().getName();
    }

    private boolean gameOver(int steps) {
        if (winner != null) {
            return true;
        }
        if (steps >= 100) {
            winner = getThreadName();
            System.out.println("胜利者是：" + winner);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        ThreadRace race = new ThreadRace();
        new Thread(race, "兔子").start();
        new Thread(race, "乌龟").start();
    }
}
